<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ry/template:message:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ry/template:message:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ry/template:message:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ry/template:message:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
  <el-button
    type="info"
    plain
    icon="el-icon-s-promotion"
    size="mini"
    @click="handleBatchSend"
    v-hasPermi="['message:template:send']"
  >批量发送</el-button>
</el-col>

<el-col :span="1.5">
  <el-button
    type="success"
    plain
    icon="el-icon-refresh"
    size="mini"
    @click="handleSyncTemplates"
    v-hasPermi="['ry/template:message:sync']"
  >同步模板</el-button>
</el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="模板ID" align="center" prop="id" /> -->
      <el-table-column label="微信模板ID" align="center" prop="templateId" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="模板内容" align="center" prop="content" />
      <el-table-column label="跳转链接规则" align="center" prop="urlRule" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ry/template:message:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ry/template:message:remove']"
          >删除</el-button>
         <el-button
      size="mini"
      type="text"
      icon="el-icon-s-promotion"
      @click="handleSend(scope.row)"
      v-hasPermi="['message:template:send']"
    >发送</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
     <!-- 修改后的对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
  >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20"> <!-- 使用栅格布局 -->
        <!-- 左列 -->
        <el-col :span="12">
        <el-form-item label="微信模板ID" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入微信模板ID" />
        </el-form-item>
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
                <el-form-item label="跳转链接规则" prop="urlRule">
          <el-input v-model="form.urlRule" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

                </el-col>
                <!-- 右列 -->
        <el-col :span="12">
        <el-form-item label="模板内容">
  <el-input
    v-model="form.content"
    type="textarea"
    :rows="8"
    placeholder="请输入模板内容（JSON格式）"
  />
</el-form-item>

       </el-col>
      </el-row>
    </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 消息发送对话框 -->
    <el-dialog title="模板发送" :visible.sync="sendDialogVisible" width="600px">
      <el-form :model="sendForm" label-width="100px">
        <el-form-item label="接收用户">
          <el-select
            v-model="sendForm.openid"
            placeholder="请选择接收用户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.openid"
              :label="`${user.nickname} (${user.openid})`"
              :value="user.openid"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择模板">
          <el-select
            v-model="sendForm.templateId"
            placeholder="请选择模板"
            @change="handleTemplateChange"
            style="width: 100%"
          >
            <el-option
              v-for="template in templateOptions"
              :key="template.templateId"
              :label="template.name"
              :value="template.templateId"
            />
          </el-select>
        </el-form-item>

        <div v-if="selectedTemplate">
          <el-form-item
            v-for="(param, key) in templateParams"
            :key="key"
            :label="key"
          >
            <el-input v-model="sendForm.params[key]" :placeholder="`请输入${key}的值`" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="sendDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSend">发送</el-button>
      </div>
    </el-dialog>


    <el-dialog title="批量发送" :visible.sync="batchSendVisible" width="600px">
  <el-form :model="batchForm" label-width="100px">
    <el-form-item label="接收用户">
      <el-select
        v-model="batchForm.openids"
        multiple
        filterable
        placeholder="请选择接收用户"
        style="width: 100%"
      >
        <el-option
          v-for="user in userList"
          :key="user.openid"
          :label="`${user.nickname} (${user.openid})`"
          :value="user.openid"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="选择模板">
      <el-select
        v-model="batchForm.templateId"
        placeholder="请选择模板"
        @change="handleBatchTemplateChange"
        style="width: 100%"
      >
        <el-option
          v-for="t in templateOptions"
          :key="t.templateId"
          :label="t.name"
          :value="t.templateId"
        />
      </el-select>
    </el-form-item>

    <div v-if="batchTemplateParams">
      <el-form-item
        v-for="(desc, key) in batchTemplateParams"
        :key="key"
        :label="key"
      >
        <el-input
          v-model="batchForm.params[key]"
          :placeholder="`请输入${desc}`"
        />
      </el-form-item>
    </div>
  </el-form>

  <div slot="footer">
    <el-button @click="batchSendVisible = false">取消</el-button>
    <el-button type="primary" @click="submitBatchSend">发送</el-button>
  </div>
</el-dialog>

  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, sendTemplate, batchSendTemplate, syncTemplates } from "@/api/ry/weixin/message";
import { listWxUser } from "@/api/ry/weixin/wxUser";

export default {
  name: "Template",
  data() {
    return {
      // 发送相关状态
      sendDialogVisible: false,
      sendForm: {
        openid: '',
        templateId: '',
        params: {}
      },
      userList: [], // 用户列表
      templateOptions: [], // 模板下拉框选项
      templateParams: {}, // 从模板内容中提取的参数键
      selectedTemplate: null, // 当前选中的模板对象
batchSendVisible: false,
    batchForm: {
      openids: [],
      templateId: '',
      params: {}
    },
    batchTemplateParams: null,


      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信消息模板管理表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "模板内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询微信消息模板管理列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 打开发送对话框 */
    async handleSend() {
      this.sendDialogVisible = true;
      this.sendForm = { openid: '', templateId: '', params: {} };
      this.templateParams = {};
      this.selectedTemplate = null;

      try {
        // 1. 获取用户列表
        const userRes = await listWxUser({ pageSize: 1000 });
        if (userRes.code === 200) {
          this.userList = userRes.rows;
        }

        // 2. 获取模板列表
        const templateRes = await listTemplate({ status: '0', pageSize: 1000 });
        if (templateRes.code === 200) {
          this.templateOptions = templateRes.rows;
        }
      } catch (e) {
        this.$message.error('获取数据失败');
      }
    },

    /** 模板选择变化时处理 */
    handleTemplateChange(templateId) {
      // 查找选中的模板
      this.selectedTemplate = this.templateOptions.find(t => t.templateId === templateId);

      if (!this.selectedTemplate) {
        this.templateParams = {};
        return;
      }

      try {
        // 解析模板内容
        const content = JSON.parse(this.selectedTemplate.content);
        this.templateParams = content.data || {};

        // 初始化参数对象
        this.sendForm.params = {};
        for (const key in this.templateParams) {
          this.$set(this.sendForm.params, key, '');
        }
      } catch (e) {
        this.$message.error('模板内容格式错误');
        this.templateParams = {};
      }
    },

    /** 提交发送 */
    async submitSend() {
      if (!this.sendForm.openid) {
        this.$message.warning('请选择接收用户');
        return;
      }

      if (!this.sendForm.templateId) {
        this.$message.warning('请选择模板');
        return;
      }

      // 检查必填参数
      for (const key in this.templateParams) {
        if (!this.sendForm.params[key]) {
          this.$message.warning(`请填写 ${key} 的值`);
          return;
        }
      }

      // 构建请求参数
      const params = {
        touser: this.sendForm.openid,
        templateId: this.sendForm.templateId,
        data: this.sendForm.params
      };

      try {
        const res = await sendTemplate(params);
        if (res.code === 200) {
          this.$message.success('发送成功');
          this.sendDialogVisible = false;
        } else {
          this.$message.error(res.msg || '发送失败');
        }
      } catch (e) {
        this.$message.error('请求失败');
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateId: null,
        name: null,
        content: null,
        urlRule: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信消息模板管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改微信消息模板管理";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除微信消息模板管理编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ry/template/message/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },

  // 打开批量发送对话框
  async handleBatchSend() {
    this.batchSendVisible = true
    this.batchForm = { openids: [], templateId: '', params: {} }
    this.batchTemplateParams = null

    // 加载用户和模板列表
    try {
      const userRes = await listWxUser({ pageSize: 1000 })
      if (userRes.code === 200) this.userList = userRes.rows

      const templateRes = await listTemplate({ status: '0', pageSize: 1000 })
      if (templateRes.code === 200) this.templateOptions = templateRes.rows
    } catch(e) {
      this.$message.error('数据加载失败')
    }
  },

  // 处理模板选择变化
  handleBatchTemplateChange(templateId) {
    const template = this.templateOptions.find(t => t.templateId === templateId)
    if (!template) return

    try {
      const content = JSON.parse(template.content)
      this.batchTemplateParams = content.data || {}
      this.batchForm.params = {}
    } catch(e) {
      this.$message.error('模板解析失败')
    }
  },

  // 提交批量发送
  async submitBatchSend() {
    // 验证数据
    if (this.batchForm.openids.length === 0) {
      return this.$message.warning('请选择接收用户')
    }
    if (!this.batchForm.templateId) {
      return this.$message.warning('请选择模板')
    }

    // 构造请求数据
    const payload = {
      templateId: this.batchForm.templateId,
      openids: this.batchForm.openids,
      params: this.batchForm.params
    }

    // 调用后端接口
    try {
      const res = await batchSendTemplate(payload)
      if (res.code === 200) {
        this.$message.success(`成功发送${res.data}条`)
        this.batchSendVisible = false
      }
    } catch(e) {
      this.$message.error('发送失败')
    }
  },

  // 同步模板
  async handleSyncTemplates() {
    this.$modal.confirm('确认从微信云端同步模板消息？').then(() => {
      this.loading = true;
      return syncTemplates();
    }).then(response => {
      this.$modal.msgSuccess("同步成功");
      this.getList();
    }).catch(() => {
      this.loading = false;
    }).finally(() => {
      this.loading = false;
    });
  }

  }
};
</script>
